package concurrent.c_000_Thread;

/**
 * 中断等待状态的线程，并抛出异常。相关方法有三个：
 * * interrupt() 是 Thread 类实例的方法，给线程中断状态设置为 false，等线程进入到等待状态时就会被中断，并抛出异常
 * * isInterrupted() 是 Thread 类实例的方法，检测线程的中断状态
 * * interrupted() 是 Thread 类的静态方法，实质调用的是 currentThread().isInterrupted(true)，作用是检测线程的中断状态，然后将状态设置为 true
 */
public class T06_Interrupt {
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "启动后的中断状态:" + Thread.currentThread().isInterrupted());

                    Thread.currentThread().interrupt();
                    System.out.println(Thread.currentThread().getName() + "interrupt()后的中断状态:" + Thread.currentThread().isInterrupted());

                    System.out.println(Thread.currentThread().getName() + "isInterrupted()获取中断状态:" + Thread.interrupted());
                    System.out.println(Thread.currentThread().getName() + "interrupted()后的中断状态:" + Thread.currentThread().isInterrupted());

                    Thread.currentThread().interrupt();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName() + "异常时中断状态:" + Thread.interrupted());
                }
            }
        };

        new Thread() {
            @Override
            public void run() {
                System.out.println(t1.getName() + "未启动时的中断状态:" + t1.isInterrupted());
                System.out.println("=======================================================");
                t1.start();
                try {
                    t1.join();
                    System.out.println("=======================================================");
                    System.out.println(t1.getName() + "执行完时的中断状态:" + t1.isInterrupted());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
